<template>

  <a-modal
      :close-on-click-modal="false"
      :open="api.editState.visible"
      :title="api.editState.title"
      destroy-on-close
      ok-text="保存"
      @cancel="api.onCloseEdit()"
      @ok="onSubmit"
  >
    <a-form
        ref="formRef"
        :model="api.editState.form"
        :rules="rules"
        :labelCol="{span: 5}"
        width="900px"
    >
      <a-form-item label="上级部门" name="pid">
        <a-tree-select
            show-search
            :tree-data="state.tree"
            v-model:value="api.editState.form.pid"
            :fieldNames="{label:'name',value:'id'}"
            placeholder="请选择上级部门"></a-tree-select>
      </a-form-item>

      <a-form-item label="名称" name="name">
        <a-input v-model:value="api.editState.form.name" allowClear placeholder="请输入名称"/>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import {OrgApi} from "~/api/system/org.api";

interface Props {
  api: OrgApi;
}

const {api} = withDefaults(defineProps<Props>(), {});

const formRef = ref();
const rules = reactive({
  pid: [{required: true, message: "请选择上级部门", trigger: "blur"}],
  name: [{required: true, message: "请输入名称", trigger: "blur"}],
});
const state = reactive({
  tree: [],
});

function getTree() {
  api.getOrgTree().then(resp => {
    if (resp.ok) {
      state.tree = resp.data;
    }
  })
}

watch(() => api.editState.visible, value => {
  if (value) {
    getTree();
  }
})

async function onSubmit() {
  const values = await formRef.value.validate();
  if (values) {
    api.submit(api.editState.form).then((res: any) => {
      if (res.ok) {
        api.onCloseEdit();
      }
    });
  }
}
</script>

<style scoped lang="scss">

</style>
